package epam.com.myThreads;

import java.util.Random;

import org.apache.log4j.Logger;


public class Auto extends Thread {

	private static final Logger log = Logger.getLogger(Auto.class
			.getName());
	public Thread threadAuto;

	public Places parking;

	private String nameAuto;

	public void setNameAuto(String name) {
		nameAuto = name;
	}

	public String getNameAuto() {
		return nameAuto;
	}

	private int residenceTime;

	public void setResidenceTime(int residenceTime) {
		this.residenceTime = residenceTime;
	}

	public int getRresidenceTime() {
		return residenceTime;
	}

	public Auto(String name, Places places) {
		this.parking = places;
		nameAuto = name;
		Random r = new Random();
		residenceTime = (r.nextInt(10) + 1) * 100;
	}

	public void run() {
		try {
			log.info("Auto '" + nameAuto
					+ "' wants to go to the parking.");
			parking.semaphore.acquire();
			for (Place item : Places.places) {
				if (item.getIsFree() == 1) {
					item.setIsFree(0);
					log.info("Auto '" + nameAuto + "' stopped at '"
							+ item.getNamePlace() + "' at " + residenceTime
							+ " millisecond.");
					Thread.sleep(residenceTime);
					item.setIsFree(1);
					log.info("Auto '" + nameAuto + "' left...");
					break;
				}
			}
			parking.semaphore.release();

		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

}
